#region Microsoft Public License
/*
 * (c) Copyright Chenjun Wu. http://utablesdk.codeplex.com
 * 
 * This source is subject to the Microsoft Public License (Ms-PL).
 * Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
 * All other rights reserved.
 */
#endregion

﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UTable.Input.MultiTouch;

namespace UTable.Objects.Handlers
{
    public class DetectContactsHandler: MultiTouchEventHandlerClass
    {
        private List<int> CurrentFingers = new List<int>();

        /// <summary>
        /// Indicate whether to mark the inputs as RouteDown
        /// The default value is false
        /// </summary>
        public bool RouteDownEvents = false;

        /// <summary>
        /// Indicate whether to mark the inputs as handled 
        /// The default value is true
        /// </summary>
        public bool HandleEvents = true;

        public override void OnMultiTouch(MultiTouchEventArgs args)
        {
            foreach (FingerEventArgs f in args.FingerEvents)
            {
                switch (f.EventType)
                {
                    case FingerEventType.FINGER_DOWN_EVENT:
                    case FingerEventType.FINGER_IN_EVENT:
                        if (!CurrentFingers.Contains(f.FingerID))
                        {
                            CurrentFingers.Add(f.FingerID);
                            if (CurrentFingers.Count == 1)
                            {
                                if (NewContact != null)
                                    NewContact(f);
                            }
                        }
                        break;
                    case FingerEventType.FINGER_OUT_EVENT:
                    case FingerEventType.FINGER_UP_EVENT:
                        if (CurrentFingers.Contains(f.FingerID))
                        {
                            CurrentFingers.Remove(f.FingerID);
                            if (CurrentFingers.Count == 0)
                            {
                                if (NoContact != null)
                                {
                                    NoContact(f);
                                }
                            }
                        }
                        break;
                }
            }
            args.RouteDown = RouteDownEvents;
            args.Handled = HandleEvents;
        }

        /// <summary>
        /// Raised when any fingers are put down on the control
        /// </summary>
        public event ContactEventHandler NewContact;

        /// <summary>
        /// Raised when all fingers are removed from the control
        /// </summary>
        public event ContactEventHandler NoContact;
    }

    public delegate void ContactEventHandler(FingerEventArgs args);
}
